package com.power.sifa.correction.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.plf.common.domain.PageDataResponse;
import com.plf.common.utils.JSONUtil;
import com.plf.core.base.service.Ha_attachmentService;
import com.plf.core.common.service.BaseServiceImpl;
import com.power.sifa.aop.service.SMService;
import com.power.sifa.correction.dao.Cre_warningDao;
import com.power.sifa.correction.model.Crc_camera;
import com.power.sifa.correction.model.Cre_warning;
import com.power.sifa.correction.model.enumeration.St_work;
import com.power.sifa.correction.model.enumeration.Tp_crc_warn;
import com.power.sifa.correction.model.pageInfo.Cre_warningPageInfo;
import com.power.sifa.correction.service.Cre_warningService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 预警信息业务层实现
 */
@Slf4j
@Service
public class Cre_warningServiceImpl extends BaseServiceImpl implements Cre_warningService {

    @Resource
    private Cre_warningDao dao;
    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    private Ha_attachmentService ha_attachmentService;
    @Resource
    private SMService smService;

    @Override
    public Cre_warning getById(Serializable id) {
        return dao.findById(id).orElse(null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(Cre_warning cre_warning) {
        // save 如果数据库不存在这条数据，就会执行保存（即将这条数据插入到数据库）；如果数据库存在这条数据，就会根据主键去更新这条数据
        if (cre_warning.getPrimaryKey() != null) {
            Cre_warning cre_warningfDb = dao.findById(cre_warning.getPrimaryKey()).orElse(null);
            if (cre_warningfDb != null) {
                BeanUtils.copyProperties(cre_warning, cre_warningfDb);
                dao.save(cre_warningfDb);
                return;
            }
        }
        dao.save(cre_warning);
    }

    @Override
    public void removeById(Serializable id) {
        dao.deleteById(id);
    }

    @Override
    public Page<Cre_warning> findAll(Cre_warningPageInfo pageInfo) {
        //排序等定义
        Sort sort;
        if ("asc".equals(pageInfo.getOrder())) {
            sort = Sort.by(Sort.Direction.ASC, pageInfo.getSort());
        } else {
            sort = Sort.by(Sort.Direction.DESC, pageInfo.getSort());
        }
        //分页的定义
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber() <= 1 ? 0 : pageInfo.getPageNumber() - 1, pageInfo.getPageSize(), sort);
        //查询条件
        Specification spec = this.createSpecification(pageInfo);
        return dao.findAll(spec, pageable);
    }

    @Transactional(rollbackFor = Exception.class)
    public void removeByIds(List<Integer> ids) {
        dao.removeByIds(ids);
    }

    @Override
    public List<Cre_warning> findAll() {
        return dao.findAll();
    }

    @Override
    public void saveAll(List<Cre_warning> list) {
        dao.saveAll(list);
    }

    @Override
    public PageDataResponse queryList(Cre_warningPageInfo pageInfo) {
        List<Cre_warning> list = this.dao.queryList(pageInfo);
        // 分页
        PageDataResponse page = new PageDataResponse();
        if (CollectionUtil.isNotEmpty(list)) {
            Long total = Long.valueOf(pageInfo.getAllcount());
            int size = pageInfo.getPageSize() * pageInfo.getPageNumber();
            if (total.intValue() - size > 0) {
                page.setNextPage(pageInfo.getPageNumber() + 1);
            }
            page.setSize(pageInfo.getPageSize());
            page.setCurrent(pageInfo.getPageNumber());
            page.setTotal(total);
        } else {
            page.setSize(0);
            page.setCurrent(1);
            page.setTotal(0L);
        }
        for (Cre_warning warning : list) {
            try {
                warning.setPername(smService.encrypt(warning.getPername()));
                warning.setDescribe(smService.encrypt(warning.getDescribe()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        page.setRecords(list);
        return page;
    }

    @Override
    public List<Cre_warning> findByCondition(Cre_warningPageInfo pageInfo) {
        Specification spec = this.createSpecification(pageInfo);
        return dao.findAll(spec);
    }

    @Override
    public List<Cre_warning> findWarningByCondition(Cre_warningPageInfo pageInfo) {
        String sql = "select w.* from cre_warning w join v_current_work vw on w.id = vw.warnid where 1 = 1 ";

        if (StringUtils.isNotBlank(pageInfo.getF_rectime()) && StringUtils.isNotBlank(pageInfo.getF_rectime_01())) {
            sql += " and w.rectime between to_timestamp('" + pageInfo.getF_rectime() + "','yyyy-MM-dd hh24:mi:ss') and  to_timestamp('" + pageInfo.getF_rectime_01() + "','yyyy-MM-dd hh24:mi:ss') ";
        }
        if (CollectionUtils.isNotEmpty(pageInfo.getF_status())) {
            sql += " and vw.status in (" + String.join(",", pageInfo.getF_status()) + ") ";
        }
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return JSONUtil.json2List(JSONUtil.obj2Json(maps), Cre_warning.class);
    }

    /**
     * 统计对应摄像头的预警信息
     *
     * @param camera
     * @param pageInfo
     * @return
     */
    @Override
    public Long countCameraWarnTotal(Crc_camera camera, Cre_warningPageInfo pageInfo) {
        Specification spec = this.createSpecification(pageInfo);
        Specification<Cre_warning> specification = (root, query, criteriaBuilder) -> query.where(
                criteriaBuilder.and(criteriaBuilder.and(criteriaBuilder.equal(root.get("lngcamera"), camera.getLng()),
                        criteriaBuilder.equal(root.get("latcamera"), camera.getLat())))
        ).select(root.get("id")).distinct(Boolean.TRUE).getRestriction();
        return dao.count(spec.and(specification));
    }

    /**
     * 统计对应摄像头处理完成的预警信息总数
     *
     * @param camera
     * @param pageInfo
     * @return
     */
    public Long countCarmeraDealTotal(Crc_camera camera, Cre_warningPageInfo pageInfo) {
        StringBuffer sql = new StringBuffer("select count(w.id) from cre_warning w join v_current_work vw on w.id = vw.warnid " +
                "where 1 = 1 ");

        if (StringUtils.isNotBlank(pageInfo.getF_rectime()) && StringUtils.isNotBlank(pageInfo.getF_rectime_01())) {
            sql.append(" and w.rectime between to_timestamp('" + pageInfo.getF_rectime() + "','yyyy-MM-dd hh24:mi:ss') " +
                    "and  to_timestamp('" + pageInfo.getF_rectime_01() + "','yyyy-MM-dd hh24:mi:ss') ");
        }
        if (CollectionUtils.isNotEmpty(pageInfo.getF_status())) {
            sql.append(" and vw.status in (" + String.join(",", pageInfo.getF_status()) + ") ");
        }
        sql.append(" and w.latcamera = " + camera.getLat() + " and w.lngcamera = " + camera.getLng());
        List<Long> result = jdbcTemplate.queryForList(sql.toString(), Long.class);
        return CollectionUtil.isNotEmpty(result) ? result.get(0) : 0L;
    }

    @Override
    public void updateIssup(String id, Integer issup) {
        this.dao.updateIssup(id, issup);
    }

    @Override
    public void updateIsrepeat(String id, Integer isrepeat) {
        this.dao.updateIsrepeat(id, isrepeat);
    }

    @Override
    public void updateIssup(List<String> ids, Integer isrepeat) {
        this.dao.updateIssup(ids, isrepeat);
    }

    @Override
    public List<Cre_warning> findListByPerid(String perid) {
        List<Cre_warning> listByPerid = this.dao.findListByPerid(perid);
        if (CollectionUtil.isEmpty(listByPerid)) {
            return null;
        }
        for (Cre_warning creWarning : listByPerid) {
            creWarning.setPhoto(ha_attachmentService.getFileUrl(creWarning.getPhoto()));
        }
        return listByPerid;
    }

    @Override
    public Page<Cre_warning> page(Cre_warningPageInfo queryPageInfo) {
        Pageable pageable = PageRequest.of(queryPageInfo.getPageNumber() - 1, queryPageInfo.getPageSize());
        Page<Cre_warning> byType = this.dao.findByType(queryPageInfo.getF_type(), pageable);
        return byType;
    }

    @Override
    public Page<Cre_warning> queryPage(Cre_warningPageInfo queryPageInfo) {
        return this.dao.queryPage(queryPageInfo);
    }

    @Override
    public PageDataResponse historicalWarning(Cre_warningPageInfo pageInfo) {
        pageInfo.setF_status(Arrays.asList(St_work.DONE));
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber() - 1, pageInfo.getPageSize());
        Page<Cre_warning> creWarnings = this.dao.historicalWarning(pageInfo, pageable);
        if (ObjectUtil.isNull(creWarnings)) {
            return null;
        }
        for (Cre_warning creWarning : creWarnings) {
            if (ObjectUtil.isNull(creWarning.getPhoto())) {
                continue;
            }
            creWarning.setPhoto(ha_attachmentService.getFileUrl(creWarning.getPhoto()));
            creWarning.setType_text(Tp_crc_warn.warnMap.get(creWarning.getType().toString()));
        }
        PageDataResponse pageResult = new PageDataResponse(creWarnings.getContent(), creWarnings.getTotalElements(),
                creWarnings.getSize(), pageable.getPageNumber() <= 1 ? 1 : pageable.getPageNumber());
        return pageResult;
    }
}
